<template>
  <a-row id="GloablHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <div>
        <a-menu
          mode="horizontal"
          :selected-keys="selectKey"
          @menu-item-click="menuItemClick"
        >
          <a-menu-item
            key="0"
            :style="{ padding: 0, marginRight: '38px' }"
            disabled
          >
            <div class="title_bar">
              <img class="logo" src="../assets/OJ.jpg" />
              <div class="title">OJ在线</div>
            </div>
          </a-menu-item>
          <a-menu-item v-for="item in visibleRoutes" :key="item.path">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </div>
    </a-col>
    <a-col flex="220px">
      <!--      登录后-->
      <div v-if="store.state.user?.loginUser.id" style="cursor: pointer">
        <a-popover position="bottom">
          <div
            style="
              display: flex;
              align-items: center;
              gap: 8px;
              cursor: pointer;
            "
          >
            <!-- 头像区域 -->
            <div style="display: flex; gap: 8px; cursor: pointer">
              <!-- 这里使用用户名首字母作为默认头像，也可以替换为实际头像图片 -->
              <a-avatar :style="{ backgroundColor: '#3370ff' }">
                <img
                  v-if="store.state.user.loginUser.userAvatar"
                  :src="store.state.user.loginUser.userAvatar"
                  alt="用户头像"
                  style="width: 100%; height: 100%; object-fit: cover"
                />
                <img
                  v-else
                  :src="'/defaultImage.png'"
                  alt="用户头像"
                  style="width: 100%; height: 100%; object-fit: cover"
                />
              </a-avatar>
            </div>
            <!-- 已登录状态（用户名 + 退出登录） -->
            <div style="display: flex; align-items: center; gap: 8px">
              <span>{{
                store.state.user?.loginUser?.userName ||
                store.state.user?.loginUser?.userAccount
              }}</span>
            </div>
          </div>
          <template #content>
            <div @click="goToHome" style="cursor: pointer">个人主页</div>
            <div @click="logout" style="cursor: pointer">退出登录</div>
          </template>
        </a-popover>
      </div>
      <!--      未登录-->
      <div v-else style="cursor: pointer">
        <div
          style="display: flex; align-items: center; gap: 8px; cursor: pointer"
        >
          <!-- 头像区域 -->
          <div style="display: flex; gap: 8px; cursor: pointer">
            <!-- 这里使用用户名首字母作为默认头像，也可以替换为实际头像图片 -->
            <a-avatar :style="{ backgroundColor: '#3370ff' }">
              <IconUser />
            </a-avatar>
          </div>

          <!-- 未登录状态 -->
          <div @click="goToLogin">去登录</div>
        </div>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import message from "@arco-design/web-vue/es/message";
import { IconUser } from "@arco-design/web-vue/es/icon";
import { routes } from "@/router/routes";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import { LoginUserVO, UserControllerService } from "../../generated";
import ACCESS_ENUM from "@/access/accessEnum";
const router = useRouter();
const notLogin = ACCESS_ENUM.NOT_LOGIN;
const menuItemClick = (key: string) => {
  router.push({
    path: key,
  });
};
//默认主页导航栏首个
const selectKey = ref(["/"]);
// 初始化时获取当前路由（解决刷新页面高亮默认为'/'问题）
onMounted(() => {
  selectKey.value = [router.currentRoute.value.path];
});
//页面跳转后，更新导航栏高亮位置
router.afterEach((to, from) => {
  selectKey.value = [to.path];
});

const store = useStore();
//更具用户身份动态显示导航栏内容
const visibleRoutes = computed(() => {
  //过滤路由 false 过滤
  return routes.filter((item, index) => {
    //过滤隐藏页面
    if (item.meta?.hideInMenu) {
      return false;
    }
    //根据权限过滤菜单
    if (!checkAccess(store.state.user.loginUser, item.meta?.access as string)) {
      return false;
    }
    return true;
  });
});
const goToLogin = () => {
  router.push("/user/login");
};
const logout = async () => {
  // 1. 调用后端退出登录接口（异步操作，需加 await）
  const res = await UserControllerService.userLogoutUsingPost();

  // 2. 检查接口响应，确认退出成功
  if (res.code === 0) {
    // 假设后端返回 { code: 0, msg: "成功" } 表示成功
    // 3. 清除前端用户状态（如 token、登录信息）
    store.state.user.loginUser = {
      userName: undefined,
      userRole: "notLogin",
    } as LoginUserVO;
    router.push("/");
    message.success("退出登录成功"); // 假设使用 Element Plus 的消息提示
  } else {
    // 接口返回失败（如 code 非 0）
    message.error(res.msg || "退出失败，请重试");
  }
};
const goToHome = () => {
  const id = store.state.user.loginUser.id;
  if (id) {
    router.push("/home");
  } else {
    router.push("/"); // 无 id 时跳转到默认主页
  }
};
</script>
<style scoped>
.title_bar {
  display: flex;
  align-items: center;
}
.title {
  color: #444;
  margin-left: 16px;
}
.logo {
  height: 48px;
}
</style>
